<?php
class Application_Model_Video extends Zend_Db_Table_Abstract{
    protected $_name = 'videos';

    public function getById($id){
        $select = $this->select()
            ->where("status = 'A' AND id = ?", $id);

        $result = $this->fetchAll($select);
        $arrVideo = $result->toArray();

        $video_number = $this->parseURl($arrVideo[0]['url']);

        $arrVideo[0]['video_number'] = $video_number;

        return $arrVideo;
    }

    public function getLast20(){
        $select = $this->select()
            ->where("status = 'A'")
            ->order('fecha DESC')
            ->limit(20);

        $result = $this->fetchAll($select);
        $arrVideos = $result->toArray();
        /*$allVideos = array();


        /*foreach($arrVideos as $v){
            $video_number = $this->parseURl($v['url']);
            $v['video_number'] = $video_number;

            array_push($allVideos, $v);
        }*/

        return $arrVideos;
    }
	
	public function getLastVideo(){
        $select = $this->select()
            ->where("status = 'A'")
            ->order('fecha DESC')
            ->limit(1);

        $result = $this->fetchAll($select);
        $arrVideos = $result->toArray();
		$arrVideo = array();
		
		foreach($arrVideos as $v){
			Zend_Loader::loadClass("Zend_Gdata_YouTube");
		   	try{
				$YouTube = new Zend_Gdata_Youtube();
				//Get the specific video
			  	$video = $YouTube->getVideoEntry($v["url"]);
			  
			  	array_push($arrVideo, $video);
		   	}catch(Zend_Service_Exception $e){ throw $e; }
		}

        return $arrVideo;
	}

    private function parseURl($url){
        $video_number =NULL;
        $arrTipo = array();

        if(strstr($url, 'v=')){
            $arrTipo = explode('v=', $url);
            $varVid = explode('&', $arrTipo[1]);
            $video_number = $varVid[0];
        }else{
            $arrTipo = explode('/', $url);
            $video_number = $arrTipo[3];
        }

        return $video_number;
    }

    public function addVideo($titulo, $url, $fecha, $status){
        $row = $this->createRow();
        $row->titulo = $titulo;
        $row->url = $url;
        $row->fecha = $fecha;
        $row->status = $status;

        $row->save();

        $id = $this->_db->lastInsertId();

        return $id;
    }
}